package com.demo.mystudy.ui.main

import android.content.Intent
import androidx.core.app.ActivityCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.demo.mystudy.R
import com.demo.mystudy.databinding.ActivityMainBinding
import com.demo.mystudy.ui.jetinnofolder.JetinnoFolderDF
import com.demo.mystudy.ui.socketclient.SocketClientDF
import com.demo.mystudy.ui.socketclient.WebSocketClientManager
import com.demo.mystudy.ui.socketserver.SocketDF
import com.demo.mystudy.ui.socketserver.WebSocketServerManager
import com.demo.mystudy.ui.usbcom.UsbcomActivity
import com.jetinno.simple.SimpleActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : SimpleActivity() {

    val mDatas = arrayListOf<MainButtonBean>()
    val mAdapter by lazy { MainAdapter(mDatas) }

    lateinit var mDB: ActivityMainBinding

    override fun useDatabing(): Boolean {
        mDB = DataBindingUtil.setContentView<ActivityMainBinding>(this, getLayoutId())
        return true
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun initView() {
        setButtonAdapter()

        lifecycleScope.launch(Dispatchers.IO){
            delay(1000)
            WebSocketServerManager.openSocket()
            delay(1000)
            WebSocketClientManager.connect("10.0.2.16", 9527)
        }

        ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
    }

    private fun setButtonAdapter() {
        mDatas.add(MainButtonBean("Socket") {
            SocketDF.showSocketDF(supportFragmentManager, getContext())
        })
        mDatas.add(MainButtonBean("SocketClient") {
            SocketClientDF.showSocketClientDF(supportFragmentManager, getContext())
        })
        mDatas.add(MainButtonBean("Usb串口") {
            startActivity(Intent(getContext(), UsbcomActivity::class.java))
        })
        mDatas.add(MainButtonBean("JetinnoFolder") {
            JetinnoFolderDF.showSocketDF(supportFragmentManager, getContext(), "Jetinno")
        })
        mDB.rvMain.run {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter
            mAdapter.setOnItemChildClickListener { adapter, view, position ->
                mDatas[position].onClickListener?.onClick(view)
            }
        }
    }

    override fun initEvent() {
    }

    override fun initData() {
    }

}